# -*- coding: utf-8 -*-
"""
用户系统 - 表单验证
"""

from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.core.exceptions import ValidationError
from .models import User
import re


class UserRegistrationForm(UserCreationForm):
    """用户注册表单"""
    
    phone = forms.CharField(
        max_length=11,
        required=True,
        label='手机号',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入手机号'
        })
    )
    
    nickname = forms.CharField(
        max_length=50,
        required=True,
        label='昵称',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入昵称'
        })
    )
    
    email = forms.EmailField(
        required=False,
        label='邮箱',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入邮箱（选填）'
        })
    )
    
    interests = forms.CharField(
        max_length=500,
        required=False,
        label='兴趣标签',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '多个兴趣用逗号分隔'
        })
    )
    
    class Meta:
        model = User
        fields = ['username', 'phone', 'email', 'nickname', 'password1', 'password2', 'interests']
        widgets = {
            'username': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入用户名'
            }),
        }
    
    def clean_phone(self):
        """验证手机号"""
        phone = self.cleaned_data.get('phone')
        
        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$', phone):
            raise ValidationError('请输入正确的手机号码')
        
        # 验证手机号是否已被注册
        if User.objects.filter(phone=phone).exists():
            raise ValidationError('该手机号已被注册')
        
        return phone
    
    def clean_username(self):
        """验证用户名"""
        username = self.cleaned_data.get('username')
        
        # 验证用户名格式（只能包含字母、数字和下划线）
        if not re.match(r'^[a-zA-Z0-9_]+$', username):
            raise ValidationError('用户名只能包含字母、数字和下划线')
        
        # 验证用户名长度
        if len(username) < 4 or len(username) > 20:
            raise ValidationError('用户名长度应在4-20个字符之间')
        
        # 验证用户名是否已存在
        if User.objects.filter(username=username).exists():
            raise ValidationError('该用户名已被使用')
        
        return username
    
    def clean_email(self):
        """验证邮箱"""
        email = self.cleaned_data.get('email')
        
        if email:
            # 验证邮箱是否已被注册
            if User.objects.filter(email=email).exists():
                raise ValidationError('该邮箱已被注册')
        
        return email
    
    def save(self, commit=True):
        """保存用户"""
        user = super().save(commit=False)
        user.phone = self.cleaned_data['phone']
        user.nickname = self.cleaned_data['nickname']
        user.interests = self.cleaned_data.get('interests', '')
        
        if commit:
            user.save()
            # 初始化隐私设置
            user.init_privacy_settings()
        
        return user


class UserLoginForm(AuthenticationForm):
    """用户登录表单"""
    
    username = forms.CharField(
        label='用户名/手机号/邮箱',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入用户名、手机号或邮箱',
            'autofocus': True
        })
    )
    
    password = forms.CharField(
        label='密码',
        strip=False,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入密码'
        })
    )
    
    remember_me = forms.BooleanField(
        required=False,
        initial=False,
        label='记住我',
        widget=forms.CheckboxInput(attrs={
            'class': 'form-check-input'
        })
    )


class UserProfileForm(forms.ModelForm):
    """用户资料编辑表单"""
    
    class Meta:
        model = User
        fields = ['nickname', 'email', 'phone', 'signature', 'interests', 'avatar']
        widgets = {
            'nickname': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入昵称'
            }),
            'email': forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入邮箱'
            }),
            'phone': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入手机号'
            }),
            'signature': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入个性签名'
            }),
            'interests': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '多个兴趣用逗号分隔'
            }),
            'avatar': forms.FileInput(attrs={
                'class': 'form-control'
            }),
        }
    
    def clean_phone(self):
        """验证手机号"""
        phone = self.cleaned_data.get('phone')
        
        if phone:
            # 验证手机号格式
            if not re.match(r'^1[3-9]\d{9}$', phone):
                raise ValidationError('请输入正确的手机号码')
            
            # 验证手机号是否被其他用户使用
            if User.objects.filter(phone=phone).exclude(pk=self.instance.pk).exists():
                raise ValidationError('该手机号已被其他用户使用')
        
        return phone
    
    def clean_email(self):
        """验证邮箱"""
        email = self.cleaned_data.get('email')
        
        if email:
            # 验证邮箱是否被其他用户使用
            if User.objects.filter(email=email).exclude(pk=self.instance.pk).exists():
                raise ValidationError('该邮箱已被其他用户使用')
        
        return email


class PasswordResetRequestForm(forms.Form):
    """密码重置请求表单"""
    
    email = forms.EmailField(
        label='邮箱',
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入注册时使用的邮箱'
        })
    )
    
    def clean_email(self):
        """验证邮箱"""
        email = self.cleaned_data.get('email')
        
        if not User.objects.filter(email=email).exists():
            raise ValidationError('该邮箱未注册')
        
        return email


class PasswordResetConfirmForm(forms.Form):
    """密码重置确认表单"""
    
    new_password1 = forms.CharField(
        label='新密码',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请输入新密码'
        })
    )
    
    new_password2 = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': '请再次输入新密码'
        })
    )
    
    def clean(self):
        """验证两次密码是否一致"""
        cleaned_data = super().clean()
        password1 = cleaned_data.get('new_password1')
        password2 = cleaned_data.get('new_password2')
        
        if password1 and password2:
            if password1 != password2:
                raise ValidationError('两次输入的密码不一致')
        
        return cleaned_data
